/**
 * ThresholdFilter.java
 * 
 * @date: 2012-02-09
 * @author: Xiaoyu Guo (MUN# 200982155)
 * This file is part of the course project for COMP 6752, 
 * Application of Computer Graphics. All the file is written
 * by myself.
 */
package mun.cs6752.project.filter.threshold;

import java.awt.image.BufferedImage;

import mun.cs6752.project.filter.abstractClasses.AbstractImageFilter;
import mun.cs6752.project.filter.abstractClasses.AbstractImageFilterControl;
import mun.cs6752.project.filter.interfaces.IImageFilterParameter;
import mun.cs6752.project.filter.interfaces.IImageProvider;

/**
 * @author Xiaoyu Guo
 *
 */
public class ThresholdFilter extends AbstractImageFilter {

    /**
     * @param provider
     * @param name
     */
    public ThresholdFilter(IImageProvider provider) {
        super(provider, "Threshold");
    }

    /* (non-Javadoc)
     * @see mun.cs6752.project.filter.interfaces.IImageFilter#execute(java.awt.image.BufferedImage, mun.cs6752.project.filter.interfaces.IImageFilterParameter)
     */
    @Override
    public BufferedImage execute(BufferedImage srcImage, IImageFilterParameter param) {
        BufferedImage destImage = new BufferedImage(
            srcImage.getWidth(), 
            srcImage.getHeight(), 
            BufferedImage.TYPE_INT_RGB
        );
        
        ThresholdFilterParameter p = null;
        if(param == null || !(param instanceof ThresholdFilterParameter)){
            p = new ThresholdFilterParameter(127);
        } else {
            p = (ThresholdFilterParameter)param;
        }
        
        for(int y = 0; y < srcImage.getHeight(); y++){
            for(int x = 0; x < srcImage.getWidth(); x++){
                int rgb = srcImage.getRGB(x, y);
                
                int r = getR(rgb);
                int g = getG(rgb);
                int b = getB(rgb);
                
                r = (r > p.getR()) ? 255 : 0;
                g = (g > p.getG()) ? 255 : 0;
                b = (b > p.getB()) ? 255 : 0;
                        
                rgb = getRGB(r, g, b);
                
                destImage.setRGB(x, y, rgb);
            }
        }
        
        return destImage;
    }

    /* (non-Javadoc)
     * @see mun.cs6752.project.filter.interfaces.IImageFilter#getControl()
     */
    @Override
    public AbstractImageFilterControl getControl() {
        return new ThresholdFilterControl(provider, this);
    }

}
